package com.example.demo.controller;

import lombok.extern.slf4j.Slf4j;
import com.example.demo.entity.Manager;
import com.example.demo.service.ManagerService;
import com.example.demo.controller.vo.ResponseResult;
import com.example.demo.utils.JwtUtils;
import com.example.demo.utils.UserContext;
import com.example.demo.exception.BusinessException;
import com.example.demo.exception.ErrorCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/admin")
public class SecurityController {

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private ManagerService managerService;


    @GetMapping("/getinfo")
    public ResponseResult<?> getInfo(@RequestHeader("token") String token) {
        Integer userId = Integer.parseInt(UserContext.getUserId());
        log.info("Fetching manager info: userId={}", UserContext.getUserId());
        Object result = managerService.getManagerInfo(userId);
        log.info("Manager info fetched successfully: userId={}", userId);
        return ResponseResult.success(result);
    }


    @PostMapping("/login")
    public ResponseResult<?> login(@RequestParam String username,
                                 @RequestParam String password) {
        log.info("Login attempt: username={}", username);
        Manager manager = managerService.getManagerByUsername(username);
        if (manager == null || !manager.getPassword().equals(password)) {
            log.warn("Login failed: username={}", username);
            throw new BusinessException(ErrorCode.USER_LOGIN_ERROR, "用户名或密码错误");
        }
        String token = jwtUtils.generateToken(manager.getUsername().toString());
        log.info("Login successful: username={}, user_id={}", username, manager.getId());
        return ResponseResult.success(new LoginResponse(token));
    }

    @PostMapping("/logout")
    public ResponseResult<?> logout(@RequestHeader("token") String token) {
        log.info("Logout attempt: username={}", UserContext.getUsername());
        jwtUtils.invalidateToken(token);
        log.info("Logout successful: username={}", UserContext.getUsername());
        return ResponseResult.success("退出登录成功");
    }

    @PostMapping("/updatepassword")
    public ResponseResult<Boolean> changePassword(@RequestHeader("token") String token,
                                                @RequestParam String oldpassword,
                                                @RequestParam String newpassword) {
        log.info("Changing password for user: username={}", UserContext.getUsername());
        Manager manager = managerService.getManagerByUsername(UserContext.getUsername());
        boolean result = managerService.changePassword(manager.getId(), oldpassword, newpassword);
        if (result) {
            log.info("Password changed successfully for user: username={}", UserContext.getUsername());
            // 使当前token失效
            jwtUtils.invalidateToken(token);
        } else {
            log.warn("Failed to change password for user: username={}", UserContext.getUsername());
        }
        return ResponseResult.success(result);
    }

    private static class LoginResponse {
        private String token;

        public LoginResponse(String token) {
            this.token = token;
        }

        @SuppressWarnings("unused")
        public String getToken() {
            return token;
        }

        @SuppressWarnings("unused")
        public void setToken(String token) {
            this.token = token;
        }
    }
}
